package com.huawei.lynnbit.tool.cocos.processor.leaf;

import com.huawei.lynnbit.tool.cocos.config.game.GameConfig;
import com.huawei.lynnbit.tool.cocos.config.game.task.DeleteFileTask;
import com.huawei.lynnbit.tool.cocos.config.game.task.DeleteStringTask;
import com.huawei.lynnbit.tool.cocos.config.game.task.Task;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class DeleteProcessor extends LeafProcessor {
    public DeleteProcessor(Task task, GameConfig gameConfig) {
        this.task = task;
        this.gameConfig = gameConfig;
    }

    @Override
    public void doProcess() throws IOException {
        processDeleteFile();
        processDeleteString();
    }

    private void processDeleteFile() {
        if (!Task.TYPE_DELETE_FILE.equals(task.getType())) {
            return;
        }

        DeleteFileTask taskInfo = (DeleteFileTask) task;
        taskInfo.presetDestPath(gameConfig);
        FileUtils.deleteQuietly(new File(taskInfo.getDestPath()));
    }

    private void processDeleteString() throws IOException {
        if (!Task.TYPE_DELETE_STRING.equals(task.getType())) {
            return;
        }

        DeleteStringTask taskInfo = (DeleteStringTask) task;
        taskInfo.presetDestPath(gameConfig);
        if (StringUtils.isNotBlank(taskInfo.getDestLine())) {
            List<String> lines = FileUtils.readLines(new File(taskInfo.getDestPath()), StandardCharsets.UTF_8);
            lines.remove(Integer.parseInt(taskInfo.getDestLine()) - 1);
            FileUtils.writeLines(new File(taskInfo.getDestPath()), StandardCharsets.UTF_8.name(), lines);
        } else {
            String context = FileUtils.readFileToString(new File(taskInfo.getDestPath()), StandardCharsets.UTF_8);
            Pattern pattern = Pattern.compile(taskInfo.getDestPattern());
            Matcher matcher = pattern.matcher(context);
            if (matcher.find()) {
                String newContext = matcher.replaceFirst("");
                FileUtils.write(new File(taskInfo.getDestPath()), newContext, StandardCharsets.UTF_8);
            } else {
                log.error("not match pattern: {}", taskInfo.getDestPattern());
                throw new IllegalStateException("not match pattern");
            }
        }

    }
}
